/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin		 	*/
/*	Project:	GlbLib-1.0.0			*/
/*	Author:		gong_libin			*/
/*	Date:		2016_06_01			*/
/*	File:		GlbSem.cpp			*/
/********************************************************/

#include "GlbSem.h"

namespace GlbIpc
{

CGlbSem::CGlbSem()
{
}

CGlbSem::~CGlbSem()
{
}

int CGlbSem::GlbIpcDelete()
{
	return semctl(CGlbIpc::m_iIpc, IPC_RMID, 0);
}

int CGlbSem::GlbIpcCreate(key_t iKey)
{
	GLBSEM_U unSem;

	if (GLB_FAILURE != (CGlbIpc::m_iIpc = semget(iKey, 1, IPC_CREAT | IPC_EXCL | 0777))) {
		unSem.m_iValue = 1;
		if (GLB_FAILURE == semctl(CGlbIpc::m_iIpc, 0, SETVAL, unSem)) {
			GLB_ERROR("%s\n", strerror(errno));
			return GLB_FAILURE;
		}
	}
	else {
		return GLB_FAILURE;
	}

	return GLB_SUCCESS;
}

int CGlbSem::GlbSemAttach(key_t iKey)
{
	if (GLB_FAILURE == (CGlbIpc::m_iIpc = semget(iKey, 1, IPC_CREAT | 0777))) {
		return GLB_FAILURE;
	}

	return GLB_SUCCESS;
}

int CGlbSem::GlbSemAcquire()
{
	struct sembuf stSem = {0, -1, SEM_UNDO};

	if (GLB_FAILURE == semop(CGlbIpc::m_iIpc, &stSem, 1)) {
		GLB_ERROR("%s\n", strerror(errno));
		return GLB_FAILURE;
	}

	return GLB_SUCCESS;
}

int CGlbSem::GlbSemRelease()
{
	struct sembuf stSem = {0, 1, SEM_UNDO};

	if (GLB_FAILURE == semop(CGlbIpc::m_iIpc, &stSem, 1)) {
		GLB_ERROR("%s\n", strerror(errno));
		return GLB_FAILURE;
	}

	return GLB_SUCCESS;
}

} /* GlbIpc */
